@using System.Linq
@using System.Xml
@using System.Xml.Linq
@using umbraco.cms.businesslogic.media
@using umbraco.MacroEngines
@inherits umbraco.MacroEngines.DynamicNodeContext
@{
    XNamespace _namespace = XNamespace.Get("http://www.itunes.com/dtds/podcast-1.0.dtd");
    XElement _xmlChannel = new XElement("channel", null);

    //===========================================================================================
    //===========================================================================================
    //Build XML output

    String _itunesTitle = CurrentModel.GetPropertyValue("itunesTitle");
    String _itunesLink = Request.Url.AbsoluteUri;
    String _itunesLanguage = CurrentModel.GetPropertyValue("itunesLanguage");
    String _itunesCopyright = CurrentModel.GetPropertyValue("itunesCopyright");
    String _itunesSubtitle = CurrentModel.GetPropertyValue("itunesSubtitle");
    String _itunesAuthor = CurrentModel.GetPropertyValue("itunesAuthor");
    String _itunesSummary = CurrentModel.GetPropertyValue("itunesSummary");
    String _itunesDescription = CurrentModel.GetPropertyValue("itunesDescription");
    String _itunesOwnerName = CurrentModel.GetPropertyValue("itunesOwnerName");
    String _itunesOwnerEmail = CurrentModel.GetPropertyValue("itunesOwnerEmail");
    int _itunesImage = CurrentModel.GetPropertyValue("itunesImage").AsInt();
    String _itunesCategories = CurrentModel.GetPropertyValue("itunesCategories");
    String _itunesBlock = (CurrentModel.GetPropertyValue("itunesBlock").AsInt() == 1) ? "Yes" : "No";
    String _itunesExplicit = (CurrentModel.GetPropertyValue("itunesExplicit").AsInt() == 1) ? "Yes" : "No";
    String _itunesKeywords = CurrentModel.GetPropertyValue("itunesKeywords");

    if (!String.IsNullOrEmpty(_itunesTitle)) { _xmlChannel.Add(new XElement("title", _itunesTitle)); }
    if (!String.IsNullOrEmpty(_itunesLink)) { _xmlChannel.Add(new XElement("link", _itunesLink)); }
    if (!String.IsNullOrEmpty(_itunesLanguage)) { _xmlChannel.Add(new XElement("language", _itunesLanguage)); }
    if (!String.IsNullOrEmpty(_itunesCopyright)) { _xmlChannel.Add(new XElement("copyright", _itunesCopyright)); }
    if (!String.IsNullOrEmpty(_itunesSubtitle)) { _xmlChannel.Add(new XElement(_namespace + "subtitle", _itunesSubtitle)); }
    if (!String.IsNullOrEmpty(_itunesAuthor)) { _xmlChannel.Add(new XElement(_namespace + "author", _itunesAuthor)); }
    if (!String.IsNullOrEmpty(_itunesSummary)) { _xmlChannel.Add(new XElement(_namespace + "summary", _itunesSummary)); }
    if (!String.IsNullOrEmpty(_itunesDescription)) { _xmlChannel.Add(new XElement("description", _itunesDescription)); }
    if (!String.IsNullOrEmpty(_itunesOwnerName) || !String.IsNullOrEmpty(_itunesOwnerEmail))
    {
        XElement _xmlOwner = new XElement(_namespace + "owner", null);
        if (!String.IsNullOrEmpty(_itunesOwnerName)) { _xmlOwner.Add(new XElement(_namespace + "name", _itunesOwnerName)); }
        if (!String.IsNullOrEmpty(_itunesDescription)) { _xmlOwner.Add(new XElement(_namespace + "email", _itunesDescription)); }
        _xmlChannel.Add(_xmlOwner);
    }

    //Add short image node
    AddImageNode(_namespace, _xmlChannel, _itunesImage);

    //Add detailed image node
    if (_itunesImage > 0)
    {
        XElement _imageNode = new XElement("image", null);

        Media _image = new Media(_itunesImage);
        if (_image.getProperty("umbracoFile") != null && !String.IsNullOrEmpty(_image.getProperty("umbracoFile").Value.ToString()))
        {
            String _imageURL = Request.Url.Host + _image.getProperty("umbracoFile").Value;
            if (!_imageURL.Contains("http://"))
            {
                _imageURL = "http://" + _imageURL;
            }

            _imageNode.Add(new XElement("url", _imageURL));
            if (!String.IsNullOrEmpty(_itunesTitle)) { _imageNode.Add(new XElement("title", _itunesTitle)); }
            if (!String.IsNullOrEmpty(_itunesLink)) { _imageNode.Add(new XElement("link", _itunesLink)); }
            _xmlChannel.Add(_imageNode);
        }
    }

    if (!String.IsNullOrEmpty(_itunesBlock)) { _xmlChannel.Add(new XElement(_namespace + "block", _itunesBlock)); }
    if (!String.IsNullOrEmpty(_itunesExplicit)) { _xmlChannel.Add(new XElement(_namespace + "explicit", _itunesExplicit)); }

    //Add categories
    if (!String.IsNullOrEmpty(_itunesCategories))
    {
        XElement _categories = XElement.Parse(_itunesCategories);

        AddCategoryNode(_namespace, _xmlChannel, _categories);
    }

    if (!String.IsNullOrEmpty(_itunesKeywords)) { _xmlChannel.Add(new XElement(_namespace + "keywords", _itunesKeywords)); }
    
    
    //Loop through child media-nodes and XML for each item
    foreach (DynamicNode _videoNode in CurrentModel.GetChildrenAsList.Items.Where(item => item.NodeTypeAlias == "AMDPodcastItem" && item.Visible == true))
    {
        AddPodcastItem(_namespace, _xmlChannel, _videoNode);
    }

    //===========================================================================================
    //===========================================================================================
    //Output XML 
    Response.ContentType = "text/xml";
    @Html.Raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + Environment.NewLine)    
    XElement _xmlRSS = new XElement("rss", new XAttribute(XNamespace.Xmlns + "itunes", _namespace), new XAttribute("version", "2.0"), _xmlChannel);
    @Html.Raw(_xmlRSS.ToString());
    
    }

    @functions{
        protected void AddImageNode(XNamespace _namespace, XElement _parent, Int32 _mediaID)
        {
            if (_mediaID > 0)
            {
                Media _image = new Media(_mediaID);
                if (_image.getProperty("umbracoFile") != null && !String.IsNullOrEmpty(_image.getProperty("umbracoFile").Value.ToString()))
                {
                    String _imageURL = Request.Url.Host + _image.getProperty("umbracoFile").Value;
                    if (!_imageURL.Contains("http://"))
                    {
                        _imageURL = "http://" + _imageURL;
                    }

                    _parent.Add(new XElement(_namespace + "image", _imageURL));
                }
            }
        }


        protected void AddCategoryNode(XNamespace _namespace, XElement _parent, XElement _propertyCategories)
        {
            foreach (XElement _propertyCategory in _propertyCategories.Elements("category"))
            {
                XElement _newCategory = new XElement(_namespace + "category", new XAttribute("text", _propertyCategory.Attribute("text").Value), null);

                AddCategoryNode(_namespace, _newCategory, _propertyCategory);

                _parent.Add(_newCategory);
            }
        }

        protected void AddPodcastItem(XNamespace _namespace, XElement _parent, DynamicNode _videoNode)
        {
            String _itunesTitle = (!String.IsNullOrEmpty(_videoNode.GetPropertyValue("itunesTitle"))) ? _videoNode.GetPropertyValue("itunesTitle") : _videoNode.Name;
            String _itunesAuthor = _videoNode.GetPropertyValue("itunesAuthor");
            String _itunesSubtitle = _videoNode.GetPropertyValue("itunesSubtitle");
            String _itunesSummary = _videoNode.GetPropertyValue("itunesSummary");
            int _itunesImage = _videoNode.GetPropertyValue("itunesImage").AsInt();
            int _itunesMediaFile = _videoNode.GetPropertyValue("itunesMediaFile").AsInt();
            DateTime _itunesPubDate = _videoNode.GetPropertyValue("itunesPubDate").AsDateTime();
            String _itunesDuration = _videoNode.GetPropertyValue("itunesDuration");
            String _itunesKeywords = _videoNode.GetPropertyValue("itunesKeywords");
            String _itunesBlock = (_videoNode.GetPropertyValue("itunesBlock").AsInt() == 1) ? "Yes" : "No";
            String _itunesExplicit = (_videoNode.GetPropertyValue("itunesExplicit").AsInt() == 1) ? "Yes" : "No";

            XElement _item = new XElement("item", null);

            if (!String.IsNullOrEmpty(_itunesTitle)) { _item.Add(new XElement("title", _itunesTitle)); }
            if (!String.IsNullOrEmpty(_itunesAuthor)) { _item.Add(new XElement(_namespace + "author", _itunesAuthor)); }
            if (!String.IsNullOrEmpty(_itunesSubtitle)) { _item.Add(new XElement(_namespace + "subtitle", _itunesSubtitle)); }
            if (!String.IsNullOrEmpty(_itunesSummary)) { _item.Add(new XElement(_namespace + "summary", _itunesSummary)); }

            AddImageNode(_namespace, _item, _itunesImage);

            if (!String.IsNullOrEmpty(_itunesBlock)) { _item.Add(new XElement(_namespace + "block", _itunesBlock)); }
            if (!String.IsNullOrEmpty(_itunesExplicit)) { _item.Add(new XElement(_namespace + "explicit", _itunesExplicit)); }

            if (_itunesMediaFile > 0)
            {
                Media _media = new Media(_itunesMediaFile);
                String _umbracoFile = (_media.getProperty("umbracoFile") != null && !String.IsNullOrEmpty(_media.getProperty("umbracoFile").Value.ToString())) ? _media.getProperty("umbracoFile").Value.ToString() : String.Empty;
                String _umbracoExtension = (_media.getProperty("umbracoExtension") != null && !String.IsNullOrEmpty(_media.getProperty("umbracoExtension").Value.ToString())) ? _media.getProperty("umbracoExtension").Value.ToString() : String.Empty;
                String _umbracoBytes = (_media.getProperty("umbracoBytes") != null && !String.IsNullOrEmpty(_media.getProperty("umbracoBytes").Value.ToString())) ? _media.getProperty("umbracoBytes").Value.ToString() : String.Empty;

                String _mediaURL = Request.Url.Host + _umbracoFile;
                if (!_mediaURL.Contains("http://"))
                {
                    _mediaURL = "http://" + _mediaURL;
                }

                XElement _enclosure = new XElement("enclosure", new XAttribute("url", _mediaURL), null);
                XElement _guid = new XElement("guid", _mediaURL);

                if (!String.IsNullOrEmpty(_umbracoBytes))
                {
                    _enclosure.Add(new XAttribute("length", _umbracoBytes));
                }
                if (!String.IsNullOrEmpty(_umbracoExtension))
                {
                    _enclosure.Add(new XAttribute("type", GetMIMEType(_umbracoExtension)));
                }

                _item.Add(_enclosure);
                _item.Add(_guid);
            }

            if (_itunesPubDate != null)
            {
                _item.Add(new XElement("pubDate", _itunesPubDate.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'")));
            }

            if (!String.IsNullOrEmpty(_itunesDuration)) { _item.Add(new XElement(_namespace + "duration", _itunesDuration)); }
            if (!String.IsNullOrEmpty(_itunesKeywords)) { _item.Add(new XElement(_namespace + "keywords", _itunesKeywords)); }

            _parent.Add(_item);
        }


        private static readonly Dictionary<string, string> MIMETypesDictionary = new Dictionary<string, string>
          {
            {"mp3", "audio/mpeg"},
            {"m4a", "audio/x-m4a"},
            {"mp4", "video/mp4"},
            {"m4v", "video/x-m4v"},
            {"mov", "video/quicktime"},
            {"pdf", "application/pdf"},
            {"epub", "document/x-epub"}
          };

        public static string GetMIMEType(string _extension)
        {
            if (MIMETypesDictionary.ContainsKey(_extension))
            {
                return MIMETypesDictionary[_extension];
            }
            return "unknown/unknown";
        }
        
    }